package problem97;

//97.交错字符串
//https://leetcode.cn/problems/interleaving-string/

class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        int n = s1.length(), m = s2.length(), k = s3.length();
        if(n+m!=k) return false;
        
        s1 = " " + s1;
        s2 = " " + s2;
        s3 = " " + s3;
        boolean[][] dp = new boolean[n+1][m+1];
        for(int i = 1; i<=n; i++) {
            if(s1.charAt(i) == s3.charAt(i)) dp[i][0] = true;
            else break;
        }
        for(int j = 1; j<=m; j++) {
            if(s2.charAt(j) == s3.charAt(j)) dp[0][j] = true;
            else break;
        }
        dp[0][0] = true;

        for(int i = 1; i<=n; i++) {
            for(int j = 1; j<=m; j++) {
                if(s1.charAt(i) == s3.charAt(i+j)) dp[i][j] = dp[i-1][j];
                if(s2.charAt(j) == s3.charAt(i+j)) dp[i][j] = dp[i][j] || dp[i][j-1];
            }
        }

        return dp[n][m];
    }
}

/*
dp[i][j]: s1的1-i个字符和s2的1-j个字符能否拼接成s3的1-i+j个字符

*/